package SSF.OS.NetFlow.Filter;

import gnu.regexp.*;
import com.renesys.raceway.DML.*;

/**
 * RERange
 * The range is specified by a Regular expression. It checks whether a given string
 * matches the regular expression.
 * <BR><I>It uses the <A HREF="http://www.cacas.org/java/gnu/regexp/">gnu.regexp</A> package by Wesley Warden Bigg.</I>
 */
public class RERange implements Range
{
    RE regularExp;

    /**
     * Config the Regular Expression Range
     * create the RE (Regular Expression) object needed
     * <BR>
     * reg_exp -- regular expression.
     * @param cfg the configuration that contains "reg_exp" attribute
     * @param dataType the type of the data that will be checked, should be String or IP here.
     */
    public void config(Configuration cfg, byte dataType) 
	throws configException
    {
	if (dataType != Decoder.STRING_TYPE &&
	    dataType != Decoder.IP_TYPE) {
	    System.err.println("Invalid dataType ("+ dataType +") for Regular Expression Range");
	    throw new configException("Invalid dataType for RERange");
	}

	String evals = (String)cfg.findSingle("reg_exp");

	if (evals == null) {
	    System.err.println("reg_exp attribute not found, please specify regular expression for RERange");
	    throw 
		new configException("reg_exp attribute not found for RERange");
	}
	else {
	    try {
		regularExp = new RE(evals);
	    }
	    catch (REException ree) {
		System.err.println(ree.getMessage());
		ree.printStackTrace();
		throw new configException("Error create RE object in RERange");
	    }
	}
    }

    /** check wether given string matches the regular expression*/
    public boolean inRange(Object data, byte dataType)
    {
	if (dataType != Decoder.STRING_TYPE &&
	    dataType != Decoder.IP_TYPE) {
	    System.err.println("Warning: Invalid dataType ("+ dataType +") for Regular Expression Range in RERange.inRange()");
	    return false;
	}	
	String str = (String)data;
	return regularExp.isMatch(str);
    }
}
